<script setup>
import {onMounted, ref} from "vue";
//引入时间格式化的方法
import {getPublishedTimeAgo} from '@/utils/time-utils'
import {getNewsListByCategory} from "@/api/news";
import {showFailToast} from "vant";
import {getNewsCategory} from "@/api/news-category";
import {throttle} from 'lodash';
import {useRouter} from "vue-router";

const router = useRouter()
//创建新闻标签
const categoryList = ref([
  {
    id: -1,
    name: '请求失败',
  }
])
// 点击标签的方法
const onClickTab = async ({name}) => {
  try {
    console.log(name)
    list.value = []// 清空列表
    nowPage.value = 1// 重置当前页数
    loading.value = false// 加载完毕
    finished.value = false// 加载完毕
  } catch (e) {
    console.log(e)
  }
}
const list = ref([]);// 列表数据
const error = ref(false);// 错误
const finished = ref(false);// 加载完毕
const loading = ref(false);// 加载中
const refreshing = ref(false)// 刷新
const nowActiveTabNewsCategoryId = ref(-1)// 当前选中的标签的id
const nowPage = ref(1)// 当前页数
const pageLimit = ref(10)// 每页的条数
// 加载更多
const throttledOnLoad = throttle(async () => {
  console.log('加载更多')
  await getNewsListByCategoryId(nowActiveTabNewsCategoryId.value);
}, 500); // 指定节流的时间间隔，单位为毫秒
// 下拉刷新加载-节流控制请求
const throttledOnRefresh = throttle(async () => {
  setTimeout(async () => {
    refreshing.value = false
    finished.value = false
    nowPage.value = 1
    list.value = []// 清空列表
    await getNewsListByCategoryId(nowActiveTabNewsCategoryId.value)
  }, 500)
}, 500); // 指定节流的时间间隔，单位为毫秒
const getNewsListByCategoryId = async (categoryId) => {
  try {
    const params = {
      page: nowPage.value,
      limit: pageLimit.value,
    }
    const res = await getNewsListByCategory(categoryId, params)
    if (res.msg !== '请求成功') {
      categoryList.value = [
        {
          id: -1,
          title: '请求失败',
        }
      ]
      const errorMsg = res.msg || '新闻获取失败'
      showFailToast(errorMsg)
      return
    }
    const resultList = res.data// 获取新闻列表
    if (resultList.length === 0) {
      finished.value = true// 加载完毕
      return
    }
    list.value.push(...resultList)// 将新闻列表添加到list中
    loading.value = false// 加载完毕
    nowPage.value++// 当前页数+1
  } catch (e) {
    console.log(e)
    const errorMsg = e || '新闻获取失败'
    showFailToast(errorMsg)
  }
}
// 获取新闻类别的方法
const getNewsCategoryList = async () => {
  try {
    const res = await getNewsCategory()
    if (res.msg !== '请求成功') {
      categoryList.value = [{id: -1, title: '请求失败',}]
      const errorMsg = res.msg || '新闻获取失败'
      showFailToast(errorMsg)
      return
    }
    categoryList.value = res.data
    // 获取第一个类别的新闻列表
    list.value = [] // 清空列表
    nowActiveTabNewsCategoryId.value = res.data[0].id// 获取第一个类别的id
  } catch (e) {
    const errorMsg = e || '获取新闻类别失败'
    showFailToast(errorMsg)
    error.value = true
    console.log(e)
  }
}
onMounted(() => {
  getNewsCategoryList()
})
// 查询新闻详情，跳转页面
const toNewsDetail = (id) => {
  console.log(id)
  router.push({path: `/news/${id}`})
}
// 写死的数据
const swipeList = [
  'https://p1.img.cctvpic.com/photoAlbum/page/performance/img/2023/4/16/1681604920337_513.png',
  'https://p1.img.cctvpic.com/photoAlbum/page/performance/img/2023/4/16/1681604951402_471.png',
  'https://p4.img.cctvpic.com/photoAlbum/page/performance/img/2023/4/16/1681605114425_295.png'
]
</script>
<template>
  <div class="home-container">
    <!--头部信息栏目-->
    <header class="home-header">
      <div class="logo"></div>
    </header>
    <!--首页的切换-->
    <van-tabs v-model:active="nowActiveTabNewsCategoryId" @click-tab="onClickTab">
      <template v-if="categoryList.length===1&&categoryList[0].id===-1">
        <van-empty description="新闻获取失败,请检查网络是否错误"/>
      </template>
      <template v-else>
        <van-tab v-for="item in categoryList" :name="item.id" :key="item.id" :title="item.name">
          <!--下拉刷新-->
          <van-pull-refresh v-model="refreshing" @refresh="throttledOnRefresh">
            <!--头部的轮播图-->
            <template v-if="item.name === '推荐'">
              <van-swipe :height="200" :autoplay="3000" class="home-swipe">
                <van-swipe-item v-for="(item,index) in swipeList" :key="index">
                  <img class="img" :src="item">
                </van-swipe-item>
              </van-swipe>
            </template>
            <!--新闻的列表样式-->
            <van-list
                style="padding-bottom: 50px;"
                v-model:loading="loading"
                v-model:error="error"
                error-text="请求失败，点击重新加载"
                :finished="finished"
                finished-text="没有更多了"
                @load="throttledOnLoad"
            >
              <!--回到顶部-->
              <van-back-top bottom="10vh"/>
              <van-cell @click.stop="toNewsDetail(item.id)" center v-for="item in list" size="large" :key="item.id"
                        class="new-list-item">
                <!--每行的标题-->
                <template #title>
                  <span class="van-multi-ellipsis--l2 left-title">{{ item.title }}</span>
                </template>
                <!--每行的详情-->
                <template #label>
              <span class="left-detail van-multi-ellipsis">
                <span class="left-detail-item source">{{ item.author }}</span>
                <span class="left-detail-item">&nbsp;·&nbsp;</span>
                <span class="left-detail-item">{{ getPublishedTimeAgo(item.publishTime) }}</span>
                <span class="left-detail-item">&nbsp;·&nbsp;</span>
                <span class="left-detail-item">{{ item.viewCount }}阅读</span>
              </span>
                </template>
                <!--右侧图片内容-->
                <template #extra>
                  <div class="right-img">
                    <img :src="item.imageUrl" alt="">
                  </div>
                </template>
              </van-cell>
            </van-list>
          </van-pull-refresh>
        </van-tab>
      </template>
    </van-tabs>
  </div>
</template>
<style scoped lang="scss">
.home-container {
  box-sizing: border-box;
  width: 100%;
  min-height: calc(100vh - 100px);
}

//头部的样式
.home-header {
  width: 100%;
  height: 75px;
  display: flex;
  align-items: center;
  background: #24a2ff;
  justify-content: center;

  .logo {
    margin-left: 20px;
    flex-basis: 100px;
    height: 50px;
    background: url("@/assets/image/logo.png") no-repeat;
    background-size: contain;
  }
}

//滚动条的样式
.home-swipe .van-swipe-item img {
  width: 100%;
  height: 100%;
}


//新闻的列表样式
.new-list-container {
  width: 100%;
  background: #fff;
}


//单行内容的样式
.new-list-item {
  width: 100%;
  height: 200px;
  padding: 0 30px;

  .left-title {
    font-size: 34px;
    color: #333;
    font-weight: 500;
  }

  .left-detail {
    margin-right: 13px;
    display: flex;
    align-items: center;
    font-size: 24px;

    &-item {
      color: #999;

      &.source {
        color: #666666;
      }
    }
  }

  .right-img {
    width: 220px;
    height: 150px;
    border-radius: 10px;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
